from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
from . import models
from pang5_web.settings import PLATFORM_LOGIN_TYPES, PLATFORMS
from pang5_web.utils import DateTimeEncoder
from work.models import Works
from platform_config.models import PlatformConfig
import time,json
from pang5_web.func import  get_uid
def index(request):
    return render(request, 'subscriber/index.html')


"""
    代码说明
    该用户的指定作品的绑定平台 
"""


def get_subscriber_plat_for_user(request):
    if request.method != 'GET':
        return HttpResponse(status=404)

    user_id = get_uid(request.COOKIES.get('pang5',''))
    print(user_id)
    subsriber_name = request.GET.get("subscriber_name", '')  # 作品名称
    if not subsriber_name:
        res = {'status': -1, "msg": '作品名不能为空'}
        return JsonResponse(res, safe=False)

    # p_ids=list(models.PlatformSubscriber.objects.filter(user_id=user_id).values("id"))
    # ids=[v['id'] for v in p_ids ]
    # ret=Works.objects.filter(platform_subsriber_id__in=idqqs,name=subsriber_name).values("platform_subsriber_id")
    # if len(ret)==0:
    #     res={'status':-1,"msg":'数据集为空'}
    #     return JsonResponse(res,safe=False)
    # return_plat=models.PlatformSubscriber.objects.filter(user_id=user_id,id__in=[x['platform_subsriber_id'] for x in ret]).values("platform")
    # if len(return_plat)==0:
    #     res={'status':-1,"msg":'绑定平台为空'}
    #     return JsonResponse(res,safe=False)

    # 以上逻辑不对
    return_plat = models.PlatformSubscriber.objects.filter(user_id=user_id, works__name=subsriber_name).values('platform')
    en_names=[x['platform'] for x in list(return_plat)]
    get_zh_name=PlatformConfig.objects.filter(platform_en__in=en_names).values('platform','platform_en')
    res_list=[]
    time_now=time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    for i in get_zh_name:
        res_list.append(i)

    return JsonResponse({'status': 0, 'info': res_list,'now':time_now},safe=False)


def subsriber_list(request):
    """
    该用户绑定的所有列表
    :param request:
    :return:
    """
    if request.method != 'GET':
        return HttpResponse(status=404)
    user_id = get_uid(request.COOKIES.get('pang5', ''))
    ps = list(models.PlatformSubscriber.objects.filter(user_id=user_id).values('id','platform','platform_login_type','platform_username','platform_status'))
    config={'0':'待校验','1':"校验通过",'2':'校验异常'}
    ret=list(PlatformConfig.objects.filter(platform_en__in=[v['platform'] for v in ps]).values('platform',"platform_en"))
    r_dect={}
    for i in ret:
        r_dect[i['platform_en']]=i['platform']
    ret=[]
    print(ps)
    for p in range(len(ps)) :
        print(ps[p])
        ret.append({})
        ret[p]["id"]=ps[p]['id']
        ret[p]["platform_en"]=ps[p]['platform']
        ret[p]["platform_login_type"]=ps[p]['platform_login_type']
        ret[p]["platform_username"]=ps[p]['platform_username']
        ret[p]["platform_status"]=ps[p]['platform_status']
        ret[p]["platform_status_zh"]=config[ps[p]['platform_status']]
        ret[p]['platform']=r_dect[ps[p]['platform']]
    print(ret)
    return JsonResponse(ret, safe=False, encoder=DateTimeEncoder)


def subsriber_bind(request):
    if request.method != 'POST':
        return HttpResponse(status=404)
    # user_id = request.user.id
    user_id = get_uid(request.COOKIES.get('pang5', ''))
    try:
        if request.POST:
            platform = request.POST['platform']
            platform_login_type = request.POST['platform_login_type']
            platform_username = request.POST['platform_username']
            platform_password = request.POST['platform_password']
        else:
            body=json.loads(request.body)
            platform = body['platform']
            platform_login_type = body['platform_login_type']
            platform_username = body['platform_username']
            platform_password = body['platform_password']

    except KeyError as e:
        j = {'status': -1, 'msg': f'{ e }参数缺失'}
        return JsonResponse(j, safe=False)
    if platform not in PLATFORMS:
        j = {'status': -1, 'msg': f'平台{platform}不存在'}
        return JsonResponse(j, safe=False)
    if   platform_login_type not in PLATFORM_LOGIN_TYPES and platform_login_type:
        j = {'status': -1, 'msg': f'登录方式{platform_login_type}不存在'}
        return JsonResponse(j, safe=False)
    obj, created = models.PlatformSubscriber.objects.update_or_create(user_id=user_id, platform=platform,
                                                                          defaults={
                                                                              'platform_login_type':platform_login_type,
                                                                              'platform_username': platform_username,
                                                                              'platform_password': platform_password,
                                                                          'platform_status':0})
    msg = '绑定创建成功' if created else '绑定修改成功'
    j = {'status': 0, 'msg': msg}
    return JsonResponse(j, safe=False)


def subsriber_delete(request):
    if request.method != 'POST':
        return HttpResponse(status=404)
    user_id = get_uid(request.COOKIES.get('pang5', ''))
    try:
        if  request.POST:
            platform = request.POST['platform']
            platform_login_type = request.POST['platform_login_type']
        else:
            body=json.loads(request.body)
            platform = body['platform']
            platform_login_type = body['platform_login_type']
    except KeyError as e:

        j = {'status': -1, 'msg': f'{ e }参数缺失'}
        return JsonResponse(j, safe=False)
    ps = models.PlatformSubscriber.objects.filter(user_id=user_id, platform=platform,
                                                  platform_login_type=platform_login_type).all()
    if len(ps) == 1:
        ps[0].delete()
        msg = '删除成功'
        j = {'status': 0, 'msg': msg}
        return JsonResponse(j, safe=False)
    j = {'status': -1, 'msg': '数据错误'}
    return JsonResponse(j, safe=False)


"""
    代码说明
    用户维度的绑定平台 
"""
def subsriber_for_user(request):
    user_id = get_uid(request.COOKIES.get('pang5', ''))
    if request.method  !="GET":
        return HttpResponse(status=404)
    platfrom=models.PlatformSubscriber.objects.filter(user_id=user_id,).values('platform')
    ret=list(PlatformConfig.objects.filter(platform_en__in=platfrom).values('platform',"platform_en"))

    return JsonResponse({'status':0,"info":ret},safe=False)
